<?php
	function RemAddEnergy($amount, $way, $cid = null)
	{
		if(!isset($cid))
		{
			$cid = $_SESSION['cid'];
			$aid = $_SESSION['uid'];
		}
		else
		{
			$aid = getAidFromCid($cid);
		}

		$current = getCharCurrEnergy($aid);
		$max = getCharMaxEnergy($aid);

		$left = $max-$current;

		if($way == 'add')
		{
			$new = $current+$amount;
		}
		else if($way == 'rem')
		{
			$new = $current-$amount;
		}

		if($new > $max)
		{
			$new = $max;
		}

		if($new < 0)
		{
			$new = 0;
		}


		//alert('Current: '.$current.'\n Max: '.$max.'\n Left: '.$left.'\n New: '.$new.'\n Amount: '.$amount);
		mysql_query("DELETE FROM energy_log WHERE cid='$cid'");
		logEnergy();
		mysql_query("UPDATE characters SET energy='$new' WHERE id='$cid'")or die(alert(mysql_error()));
	}

	function logEnergy($cid = null)
	{
		if(!isset($cid))
		{
			$cid = $_SESSION['cid'];
			$aid = $_SESSION['uid'];
		}
		else
		{
			$aid = getAidFromCid($cid);
		}

		mysql_query("INSERT INTO energy_log (cid, time) VALUES ('".$cid."', '".time()."')");
	}



	$cid = $_SESSION['cid'];
	$aid = $_SESSION['uid'];
	$current = getCharCurrEnergy($aid);
	$max = getCharMaxEnergy($aid);
	if($current < $max)
	{
		$q = mysql_query("SELECT * FROM energy_log WHERE cid='$cid' ORDER BY time DESC LIMIT 1");
		if(mysql_num_rows($q) == 0)
		{
			logEnergy();
		}
		else
		{
			$f = mysql_fetch_array($q);
			$currenttime = time();

			$difference = $currenttime-$f['time'];

			$time = 60;
			$amount = 1;

			if($difference > $time)
			{
				$math = $difference/$time;
				$amount = floor($amount*$math);
			}
			

			if($difference >= $time)
			{
				RemAddEnergy($amount, 'add');
				logEnergy();
			}
		}
	}
	

?>